$(function() { //document/window load
	$('#droppable').html($("#content").val()); // set the form structure to the canvass
	$(".datepicker").val("04/17/2013");
	$(".datepicker").datepicker();
	$(".datepicker").datepicker();
	
	//datepicker object
	
	var tblName = $("#tblName").val(); // get the Table Name from the query string
	var id = $("#requestID").val(); // get the Request ID from the query string
	var buttons = $("#buttons").val();
	
	appendButtons(buttons)
	$('#droppable').css('min-width','950px'); // set the canvass to Minimum Width of 950px
	$(".bluebutton").click(function(){
		saveForm("submit") // save forms
	});
	
	if($(window).width()<1224){ // if window size is less than 1224 px
		$('#rNav').hide(); // hide the quick navigation panel
		$('#droppable').css('width','950'); // set the canvass size to 950px
	}else{
		$('#rNav').show(); // display the quick navigation panel
		$('#droppable').css('width',$(window).width()-300); // set the canvass size equals to the window width minus 300px
		$('#divLog').css('height',$(window).height()-400);	 // set the audit log panel height equals to the window height minus 400px
	}
	
	$(window).resize(function(){ //on window resize
		if($(window).width()<1224){ //if window size is less than 1224 px
			$('#rNav').hide();// hide the quick navigation panel
		}else{
			$('#rNav').show(); // display the quick navigation panel
			$('#droppable').css('width',$(window).width()-300); // set the canvass size equals to the window width minus 300px
			$('#divLog').css('height',$(window).height()-400);	// set the audit log panel height equals to the window height minus 400px
		}
	});
	
	if(id==0){// if is new document
		var trackNo = CreateTrackNumber("PR","Stephen Curry") // create tracking number of the request
		$("#TrackNo").val(trackNo); // set field TrackNo equals to the created tracking number
		$("#tmpTrackNo").text(trackNo); // set field tmpTrackNo equals to the created tracking number	
	}else{
		// if is document is being edited
		getDetails(tblName, id); //get the request details according to table id and request id
	}
	
		
	$("#commentPost").click(function(){ // set action for comment button post
		var comment = $("#txtComment").val(); // get comment from field txtComment
		addComment(tblName, id, comment) // add request comment according to table name, request id, comment
	});
	
	
});

function getDetails(tblName, id){ // get request details according to table id and request id
	$.ajax({ 
		url: "/requestJSON/" + tblName + "/" + id ,// request details web service path
		success: function( results){ // on fetch success
			for(var key in results){
				for(var subKey in results[key]){
				   setDetails(subKey,results[key][subKey]);
				}
			}
			addComment(tblName, id); //load request comments
		}
	});
}


function setDetails(fieldName, fieldValue){//set request details according to fieldName and field value
	//
	var elementType =  String($('[name="' + fieldName + '"]').attr('type')); // get the element type base on field name
	if(elementType=="checkbox" || elementType=="radio" ){ // check if the element is either checkbox or radio button object
		var options = $('[name="' + fieldName + '"]'); //get all the options or selections of the object
		for(var i=0;i<options.length;i++){ //loop the selections length
			if(fieldValue.indexOf(options[i].value)>-1){ // check if the field value is within the selection
				$(options[i]).prop('checked', true); // check the option
			}
		}
	}else{
		$('[name="' + fieldName + '"]').val(fieldValue); // set the field value according to field name
	}
}

function CreateTrackNumber(type,username) // create request tracking number according to username and request type
{
	var d = new Date(); // get current date

	var curr_hour = d.getHours(); // get current date hour
	var curr_min = d.getMinutes(); // get current date minutes
	var curr_sec = d.getSeconds(); // get current date seconds
	var curr_milsec = d.getMilliseconds(); // get current date milli seconds
	var curr_month = d.getMonth() + 1; // get current date month plus one
	var curr_day = d.getDate(); // get current date day
	var curr_year = d.getYear(); // get current date year
	
	var str = username;	// set equals to the current user name
	var str_split = str.split(" "); // split current user name with space to determine the first name and last name
	var fname = Left(str_split[0].toUpperCase(),1); // get the first element of the array to get the first name
	var lname; //Last Name

	if (str_split.length > 1)
		lname = Left(str_split[str_split.length-1].toUpperCase(),1); // get the last name
	else
		lname = Right(str_split[0].toUpperCase(),1); // get the last name
		
	var str_month = String(curr_month) //convert curr_month to string
	var str_day = String(curr_day) // convert curr_day to string
	if (str_month.length < 2) 
		str_month = '0' + str_month // format month to 'mm'
	if (str_day.length < 2)
		str_day = '0' + str_day // format day to 'dd'
		
	var trackno = String(fname) + String(lname) + type  + str_month +str_day  + String(curr_year) +
	String(curr_hour) + String(curr_min) + String(curr_sec) + String(curr_milsec); // concatinate First Name, Last Name, Request Type, Current Month, Current Year, Current Hour, Current Minute, Current Seconds, Current Milliseconds 
	
	return trackno;
}

function Left(str, n){ // left function
	//str - String content
	//n - index
	if (n <= 0) //check if index is equal to zero
	    return ""; // return null value
	else if (n > String(str).length) // check if index is greater than the length of the string content
	    return str; // return as is value of the string
	else
	    return String(str).substring(0,n); // return value from string start until index
}

function saveForm(lastAction){ // save the request
	var newDate = new Date(); // assign request date created
	$("#DateCreated").val(newDate.toISOString()); // assign date created value to DateCreated field
	$("#Unread").val("1");// set request as unread
	
	document.frmForm.submit();// submit the request
}


function addComment(tblName, id, comment){// add request comment
	$.ajax({
		url: "/comment/" + tblName + "/" + id + "/" +  comment, // comment details web service path
		cache: false
		}).done(function( data ) { // on fetch success
			$("#txtComment").val(""); // clear comment text area field
			$("#divComment").html(""); // clear comment log panel
			//$("#divComment").append(html); // append return data from webservice to the comment log panel
			
			var output = '<table border=0 cellpadding=2 cellspacing=0 width="100%">';
			var users=["Stephen Cury","Harrison Barnes", "Kent Bazemore", "Andris Biedrins", "Andrew Bogut", "Festus Ezeli", "Draymond Green"];
			
			for(var i=0, l=data.length; i<l; i++){
				output += '<tr class="rightNavRow">';
				output += '<td valign="top" width="20px" style="border-bottom: 1px solid rgb(49, 49, 49);border-top: 1px solid rgb(96, 96, 96);"><img src="/images/1.jpg" width="30px" height="40px"></td>';
				output += '<td style="border-bottom: 1px solid rgb(49, 49, 49);border-top: 1px solid rgb(96, 96, 96);"><b>'+ users[i] + ': </b>' + data[i].Content + '<br /><br /> <font color="#ccc"><abbr class="timeago" title="' + data[i].DateCreated + '"> '+ data[i].DateCreated +'</abbr></td>';
				output += '</tr>';
			}	
			
			output += '</table>';
			$("#divComment").append(output);
			
			$("#divComment").jScrollPane({ // jquery plugin for facebook like scrollbar
				horizontalGutter:5,
				verticalGutter:5,
				'showArrows': false,
				autoReinitialise: true
			});
			
			$('.jspDrag').hide(); // hide scroll bar
			$('.jspScrollable').mouseenter(function(){
				$(this).find('.jspDrag').stop(true, true).fadeIn('slow'); // show scroll bar on mouse over
			});
				
			$('.jspScrollable').mouseleave(function(){
				$(this).find('.jspDrag').stop(true, true).fadeOut('slow'); // hide scroll bar on mouse leave
			});
			jQuery("abbr.timeago").timeago(); // jquery plugin for facebook like TIME ELAPSED
	});
}

function appendButtons(buttons){
	var buttonArray = buttons.split(",");
	for(var i=0;i<buttonArray.length;i++){
		$("#divActionBar").append('<a class="bluebutton" href="#">' + buttonArray[i] + "</a>&nbsp;");
	}
	
}
